package com.cyy.map;

import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

/**
 * 哈希表  HashMap 直接使用红黑树实现
 * JDK中的HashMap底层一开始是使用链表，当哈希表容量 >= 64 且单向链表的节点数量大于 8 时
 * JDK 中的 HashMap 就转换成为 红黑树
 * @author 会玩的洋洋
 * @since 2022-03-01
 * @param <K>
 * @param <V>
 */
public class HashMap<K, V> implements Map<K, V> {
    private final static boolean RED = false;
    private final static boolean BLACK = true;
    private int size;
    /**
     * 存储数据的tables
     */
    private Node<K, V>[] tables;
    /**
     * 默认大小
     */
    private final static int DEFAULT_CAPACITY = 1 << 4;

    /**
     * 负载因子  JDK 也是 0.75f
     */
    private final static float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashMap() {
        this(DEFAULT_CAPACITY);
    }

    public HashMap(int capacity) {
        if (capacity % 2 == 0) {
            capacity = Math.max(DEFAULT_CAPACITY, capacity);
        } else {
            capacity = DEFAULT_CAPACITY;
        }
        this.tables = new Node[capacity];
        this.size = 0;
    }

    protected static class Node<K, V> {
        int hash;
        K key;
        V value;
        Node<K, V> parent;
        Node<K, V> left;
        Node<K, V> right;
        boolean color = RED;

        public Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            int hash = key == null ? 0 : key.hashCode();
            // 扰动计算
            this.hash = hash ^ (hash >>> 16);
            this.value = value;
            this.parent = parent;
        }
        public Node() {
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

        public boolean isLeftChild() {
            return parent != null && parent.left == this;
        }

        public boolean isRightChild() {
            return parent != null && parent.right == this;
        }

        public Node<K, V> sibling() {
            if (isLeftChild()) {
                return parent.right;
            } else if (isRightChild()) {
                return parent.left;
            }
            return null;
        }
    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public boolean isEmpty() {
        return this.size == 0;
    }

    @Override
    public void clear() {
        if (size == 0) {
            return;
        }
        size = 0;
        for (int i = 0; i < tables.length; i++) {
            tables[i] = null;
        }
    }

    @Override
    public V put(K key, V value) {
        resize();

        int index = index(key);
        Node<K, V> root = tables[index];
        // 对于 tables 中对应节点第一次添加的元素
        if (root == null) {
            root = createNode(key, value, null);
            tables[index] = root;
            size++;
            fixAfterPut(root);
            return null;
        }

        // 添加的不是第一个节点
        Node<K, V> parent = root;
        Node<K, V> node = root;
        Node<K, V> result = null;
        // 计算key 对应的hashCode
        int hash = hash(key);
        // 用于判断是否已经搜索过了
        boolean searched = false;
        int cmp = 0;
        do {
            parent = node;
            int h2 = node.hash;
            K k2 = node.key;

            // 先比较hash值大小
            if (hash > h2) {
                cmp = 1;
            } else if (hash < h2) {
                cmp = -1;
            } else if (Objects.equals(key, k2)) {
                // 比较两个 key 是否相同
                cmp = 0;
            } else if (key != null && k2 != null
                    && key.getClass() == k2.getClass()
                    && key instanceof Comparable
                    && (cmp = ((Comparable) key).compareTo(k2)) != 0) {

            } else if (searched) {
                // 如果已经搜索过
                cmp = System.identityHashCode(key) - System.identityHashCode(k2);
            } else {
                // 扫描
                if ((node.left != null && (result = node(node.left, key)) != null)
                        || (node.right != null && (result = node(node.right, key)) != null)) {
                    // 查找到了
                    node = result;
                    cmp = 0;
                } else {
                    // 没有查找到，随便插入即可
                    searched = true;
                    cmp = System.identityHashCode(key) - System.identityHashCode(k2);
                }
            }

            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                node.key = key;
                V oldValue = node.value;
                node.value = value;
                node.hash = hash;
                return oldValue;
            }
        } while (node != null);

        // 找到需要插入的地方
        Node<K, V> newNode = createNode(key, value, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        ++size;

        // 新添加之后 进行旋转操作
        fixAfterPut(newNode);
        return null;
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(key);
        return node == null ? null : node.value;
    }

    @Override
    public V remove(K key) {
        return remove(node(key));
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        if (size == 0) {
            return false;
        }
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < tables.length; i++) {
            if (tables[i] == null) {
                continue;
            }
            queue.offer(tables[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (Objects.equals(node.value, value)) {
                    return true;
                }

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return false;
    }

    @Override
    public void traversal(Visitor<K, V> visitor) {
        if (size == 0 || visitor == null) {
            return;
        }
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < tables.length; i++) {
            if (tables[i] == null) {
                continue;
            }
            queue.offer(tables[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (visitor.visit(node.key, node.value)) {
                    return;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
    }

    /**
     * 创建node节点
     * @param key 键
     * @param value 值
     * @param parent 父节点
     * @return Node<K, V>
     */
    protected Node<K, V> createNode(K key, V value, Node<K, V> parent) {
        return new Node<K, V>(key, value, parent);
    }

    /**
     * 删除之后的操作 让子类重写
     * @param willedNode 要删除的节点
     * @param removedNode 删除的节点 或 被替代的节点
     */
    protected void afterRemove(Node<K, V> willedNode, Node<K, V> removedNode) {

    }

    /**
     * 扩容操作
     */
    private void resize() {
        // 如果没有超过负载因子，无需扩容
        if (((float) size / tables.length) <= DEFAULT_LOAD_FACTOR) {
            return;
        }

        // 扩容操作
        Node<K, V>[] oldTables = tables;
        tables = new Node[oldTables.length << 1];

        // 对每个数组中的红黑树进行层序遍历 存储
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < oldTables.length; i++) {
            if (oldTables[i] == null) {
                continue;
            }
            queue.offer(oldTables[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                moveNode(node);
            }
        }
    }

    /**
     * 移动节点  为扩容做准备
     * 将节点移动到新数组
     * @param newNode 要移动的节点
     */
    private void moveNode(Node<K, V> newNode) {
        // 清除节点相关属性
        newNode.left = null;
        newNode.right = null;
        newNode.parent = null;
        newNode.color = RED;

        // 重复添加操作
        int index = index(newNode);
        Node<K, V> root = tables[index];
        if (root == null) {
            root = newNode;
            tables[index] = root;
            fixAfterPut(root);
            return;
        }

        /*
            因为是将一个 哈希表 中的值移到另一个哈希表 则不需要判断 cmp == 0 的情况
         */
        Node<K, V> parent = root;
        Node<K, V> node = root;
        int cmp = 0;
        K k1 = newNode.key;
        int h1 = newNode.hash;
        do {
            parent = node;
            K k2 = node.key;
            int h2 = node.hash;

            if (h1 > h2) {
                cmp = 1;
            } else if (h1 < h2) {
                cmp = -1;
            } else if (k1 != null && k2 != null
                    && k1.getClass() == k2.getClass()
                    && k1 instanceof Comparable
                    && (cmp = ((Comparable) k1).compareTo(k2)) != 0) {

            } else {
                cmp = System.identityHashCode(k1) - System.identityHashCode(k2);
            }

            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            }
        } while(node != null);

        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        newNode.parent = parent;
        fixAfterPut(newNode);
    }
    /**
     * 根据传入的节点  对该节点进行删除操作
     * @param node 要删除的节点
     * @return 删除节点的值
     */
    private V remove(Node<K, V> node) {
        if (node == null) {
            return null;
        }

        --size;
        V oldValue = node.value;

        Node<K, V> willedNode = node;

        // 先判断是否是度为2的节点
        if (node.hasTwoChildren()) {
            // 查找该节点的前驱或者后继
            Node<K, V> successor = successor(node);
            // 将前驱或者后继节点元素覆盖该节点
            node.key = successor.key;
            node.value = successor.value;
            node.hash = successor.hash;
            // 将node 置为 前驱或者后继节点，为后续的删除 度为 1 或 0 的节点做准备
            node = successor;
        }

        // 获取替代元素
        Node<K, V> replaceNode = node.left != null ? node.left : node.right;
        int index = index(node);
        // 如果不是叶子节点  即  replaceNode != null
        if (replaceNode != null) {
            // 度为 1 的节点
            replaceNode.parent = node.parent;
            if (node.parent == null) {
                // 该节点为根节点
                tables[index] = replaceNode;
            } else if (node.parent.left == node) {
                // 如果是该节点是左子树
                node.parent.left = replaceNode;
            } else {
                // 该节点为右子树
                node.parent.right = replaceNode;
            }

            fixAfterRemove(replaceNode);
        } else if (node.parent == null){
            // 该节点为根节点 且 根节点为叶子节点
            tables[index] = null;

            fixAfterRemove(node);
        } else {
            // 叶子节点  度为 0
            if (node.parent.left == node) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }

            fixAfterRemove(node);
        }

        afterRemove(willedNode, node);
        return oldValue;
    }
    /**
     * 扰动计算  直接返回扰动计算后的hash值
     * @param key 传入的key
     * @return 扰动计算后的hash值
     */
    private int hash(K key) {
        if (key == null) {
            return 0;
        }
        int hash = key.hashCode();
        return hash ^ (hash >>> 16);
    }

    /**
     * 通过 key 的哈希计算 计算出应该存入tables的下标
     * @param key 需要计算的key
     * @return int  key 对应的下标
     */
    private int index(K key) {
        return hash(key) & (tables.length - 1);
    }

    /**
     * 通过节点计算下标
     * @param node 目标节点
     * @return int
     */
    private int index(Node<K, V> node) {
        return node.hash & (tables.length - 1);
    }

    /**
     * 通过 key 查找节点
     * @param key 键
     * @return Node<K, V>
     */
    private Node<K, V> node(K key) {
        Node<K, V> root = tables[index(key)];
        return root == null ? null : node(root, key);
    }

    /**
     * 通过 key 搜索红黑树中 的节点
     * @param node 红黑树节点
     * @param k1 键
     * @return Node<K, V>
     */
    private Node<K, V> node(Node<K, V> node, K k1) {
        int h1 = hash(k1);
        Node<K, V> result = null;
        int cmp = 0;
        while (node != null) {
            K k2 = node.key;
            int h2 = node.hash;
            // 先比较哈希值
            if (h1 > h2) {
                node = node.right;
            } else if (h1 < h2) {
                node = node.left;
            } else if (Objects.equals(k1, k2)) {
                // 比较两个键是否相等
                return node;
            } else if (k1 != null && k2 != null
                    && k1.getClass() == k2.getClass()
                    && k1 instanceof Comparable
                    && (cmp = ((Comparable) k1).compareTo(k2)) != 0) {
                node = cmp > 0 ? node.right : node.left;
            } else if (node.right != null && (result = node(node.right, k1)) != null) {
                // 递归搜索
                return result;
            } else {
                // 只能向左找
                node = node.left;
            }
        }
        return null;
    }

    /**
     * 左旋转
     * @param grand 需要旋转的节点
     */
    private void leftRotate(Node<K, V> grand) {
        if (grand == null) {
            return;
        }
        Node<K, V> parent = grand.right;
        Node<K, V> child = parent.left;
        grand.right = child;
        parent.left = grand;

        afterRotate(grand, parent, child);
    }

    /**
     * 右旋转
     * @param grand 需要旋转的节点
     */
    private void rightRotate(Node<K, V> grand) {
        if (grand == null) {
            return;
        }
        Node<K, V> parent = grand.left;
        Node<K, V> child = parent.right;
        grand.left = child;
        parent.right = grand;

        afterRotate(grand, parent, child);
    }

    /**
     * 旋转之后的修复操作
     * @param grand 祖父节点
     * @param parent 父节点
     * @param child 子节点
     */
    private void afterRotate(Node<K, V> grand, Node<K, V> parent, Node<K, V> child) {
        parent.parent = grand.parent;
        if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else if (grand.isRightChild()) {
            grand.parent.right = parent;
        } else {
            tables[index(grand)] = parent;
        }

        if (child != null) {
            child.parent = grand;
        }
        grand.parent = parent;
    }

    private Node<K, V> color(Node<K, V> node, boolean color) {
        if (node == null) {
            return null;
        }
        node.color = color;
        return node;
    }

    private Node<K, V> red(Node<K, V> node) {
        return color(node, RED);
    }

    private Node<K, V> black(Node<K, V> node) {
        return color(node, BLACK);
    }

    private boolean colorOf(Node<K, V> node) {
        return node == null ? BLACK : node.color;
    }

    private boolean isBlack(Node<K, V> node) {
        return node == null || node.color == BLACK;
    }

    private boolean isRed(Node<K, V> node) {
        return colorOf(node) == RED;
    }

    /**
     * 添加后的操作
     * @param node 添加的节点
     */
    private void fixAfterPut(Node<K, V> node) {
        Node<K, V> parent = node.parent;
        if (parent == null) {
            black(node);
            return;
        }

        if (isBlack(parent)) {
            return;
        }

        Node<K, V> uncle = parent.sibling();
        Node<K, V> grand = red(parent.parent);
        if (isRed(uncle)) {
            black(uncle);
            black(parent);
            fixAfterPut(grand);
            return;
        }

        if (parent.isLeftChild()) {
            if (node.isLeftChild()) {
                black(parent);
            } else {
                leftRotate(parent);
                black(node);
            }
            rightRotate(grand);
        } else {
            if (node.isRightChild()) {
                black(parent);
            } else {
                rightRotate(parent);
                black(node);
            }
            leftRotate(grand);
        }
    }

    /**
     * 删除之后的操作
     * @param node 删除的节点或被替代的节点
     */
    private void fixAfterRemove(Node<K, V> node) {
        if (isRed(node)) {
            black(node);
            return;
        }
        Node<K, V> parent = node.parent;
        if (parent == null) {
            return;
        }

        boolean left = parent.left == null || node.isLeftChild();
        Node<K, V> sibling = left ? parent.right : parent.left;

        if (left) {
            if (isRed(sibling)) {
                black(sibling);
                red(parent);
                leftRotate(parent);
                sibling = parent.right;
            }

            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentBlack = isBlack(parent);
                red(sibling);
                black(parent);
                if (parentBlack) {
                    fixAfterRemove(parent);
                }
            } else {
                if (isBlack(sibling.right)) {
                    rightRotate(sibling);
                    sibling = parent.right;
                }
                color(sibling, colorOf(parent));
                black(parent);
                black(sibling.right);
                leftRotate(parent);
            }
        } else {
            if (isRed(sibling)) {
                black(sibling);
                red(parent);
                rightRotate(parent);
                sibling = parent.left;
            }

            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentBlack = isBlack(parent);
                red(sibling);
                black(parent);
                if (parentBlack) {
                    fixAfterRemove(parent);
                }
            } else {
                if (isBlack(sibling.left)) {
                    leftRotate(sibling);
                    sibling = parent.left;
                }
                color(sibling, colorOf(parent));
                black(parent);
                black(sibling.left);
                rightRotate(parent);
            }
        }
    }

    /**
     * 获取后继节点
     * @param node 目标节点
     * @return Node<K, V>
     */
    private Node<K, V> successor(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        Node<K, V> s = node.right;
        if (s != null) {
            while (s.left != null) {
                s = s.left;
            }
            return s;
        }

        while (node.parent != null && node.parent.right == node ) {
            node = node.parent;
        }
        return node.parent;
    }

    /**
     * key 非空判断
     * @param key 键
     */
    private void keyNotNullCheck(K key) {
        if (key == null) {
            throw new IllegalArgumentException("Key is not be empty!!");
        }
    }
}
